import { ChangeDetectionStrategy, ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { I18NService, MenuItem } from '@iux/live';
import { uniqueId } from 'lodash';

interface DemoUser {
  id: string;
  name: string;
  age: number;
  random: number;
}

@Component({
  templateUrl: './use-in-table.component.html',
  styles: [
    `
      .table {
        width: 100%;
      }
    `,
  ],
  changeDetection: ChangeDetectionStrategy.OnPush,
})
export class UseInTableComponent implements OnInit {
  data: DemoUser[];
  dataItems: MenuItem[];
  edit = this.i18n.get('Edit');
  file = this.i18n.get('File');

  constructor(private i18n: I18NService, private cdr: ChangeDetectorRef) {}

  ngOnInit() {
    setTimeout(() => {
      this.initData();
    }, 500);
  }

  initData() {
    this.data = Array.from({ length: 5 }).map((item, key) => this.initUser(key));
    this.cdr.markForCheck();
  }

  initUser(key: number) {
    return {
      id: uniqueId('uid'),
      name: `user${key}`,
      age: 10 + key,
      random: parseInt(`${Math.random() * 100}`, 10),
    };
  }

  getItems = data => {
    this.dataItems = [
      {
        id: 'Edit',
        label: this.edit,
        onClick: e => {
          console.log(e);
          console.log(data);
        },
      },
      {
        id: 'VM',
        label: 'Deploy VM from Template',
        tips: data.age === 10 ? 'This is disabled tips' : '',
        disabled: data.age === 10,
        hidden: data.age === 15,
        onClick: e => {
          console.log(e);
          console.log(data);
        },
        divide: true,
      },
      {
        id: 'File',
        label: this.file,
        items: [
          {
            id: 'File-Create',
            label: 'Create',
            hidden: data.age === 15,
          },
          {
            id: 'File-Open',
            label: 'Open',
            disabled: data.age === 15,
          },
        ],
      },
    ];

    if (data.age === 12) {
      this.dataItems = [this.dataItems[0], this.dataItems[1]];
    }

    const options = this.dataItems.filter(item => !item.hidden);
    return options || [];
  };

  trackByFn(index: number, item: any): number {
    return item.id;
  }

  Refresh() {
    this.data[0].age = this.data[0].age === 10 ? 12 : 10;
    this.data[1].age = this.data[1].age === 11 ? 15 : 11;
  }
}
